<?php

class Parametricos_AplicacionController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
        $parametrosNamespace->unlock ();
        $parametrosNamespace->parametrosBusqueda = null;
        $parametrosNamespace->cantidadFilas = null;
        $parametrosNamespace->jsGrip = '/js/grillasmodulos/parametricos/gridAplicacion.js';
        $parametrosNamespace->Application_Model_DbTable = "Application_Model_DbTable_Aplicacion";
        $parametrosNamespace->busqueda = "desc_aplicacion";
        $parametrosNamespace->lock ();
    }

    public function listarAction() {
        
		$this->_helper->viewRenderer->setNoRender ( true );

		$cantidadFilas = $this->getRequest ()->getParam ( "rows" );
		if (! isset ( $cantidadFilas )) {
			$cantidadFilas = 10;
		}
		$parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
		$parametrosNamespace->unlock();
		$parametrosNamespace->cantidadFilas = $cantidadFilas;

		$page = $this->getRequest ()->getParam ( "page" );
		if (! isset ( $page )) {
			$page = 1 ;
		}

		$this->view->headScript ()->appendFile ( $this->view->baseUrl () . '/js/bootstrap.js' );
	 	$this->view->headScript ()->appendFile ( $this->view->baseUrl () . $parametrosNamespace->jsGrip );

	 	$where = $parametrosNamespace->parametrosBusqueda;
                $order = array('B.desc_modulo asc');
                if(!isset($where)) $where = 1;
                $db = Zend_Db_Table::getDefaultAdapter();
                $select = $db->select()
                         ->from(array('A' => 'aplicacion'), 
                           array('A.cod_aplicacion','B.desc_modulo','A.desc_aplicacion','A.activo'))
                         ->join(array('B' => 'modulo_aplicacion'),'A.cod_modulo = B.cod_modulo',array('B.cod_modulo'))
                         ->where($where)
                         ->order($order);
                $result = $db->fetchAll($select);
		$parametrosNamespace->lock();
                $pagina = self::obtenerPaginas($result,$cantidadFilas,$page);
		echo $this->_helper->json ( $pagina );
	}

	private function obtenerPaginas($result,$cantidadFilas,$page){
		$this->_paginator = Zend_Paginator::factory ($result);
	 	$this->_paginator->setItemCountPerPage ( $cantidadFilas );
	 	$this->_paginator->setCurrentPageNumber($page);
		$pagina ['rows'] = array ();
		foreach ( $this->_paginator as $item ) {
                        if($item["activo"] == 'S') $activo = 'Activo'; 
                        else $activo = 'Desactivado';
                        
			$arrayDatos ['cell'] = array(
                            $item["cod_aplicacion"],
                            null,
                            trim(utf8_encode($item["desc_modulo"])),
                            trim(utf8_encode($item["desc_aplicacion"])),
                            $activo,
                            $item["cod_modulo"],
                            $item["activo"]);
                        
			$arrayDatos ['columns'] = array(
                            "id",
                            "modificar",
                            "desc_modulo",
                            "desc_aplicacion",
                            "desc_activo",
                            "cod_modulo",
                            "activo");
                        
			array_push ( $pagina ['rows'],$arrayDatos);
		}           
		$pagina ['records'] = count ( $result );
		$pagina ['page'] = $page;
		$pagina ['total'] = ceil ( $pagina ['records'] / $cantidadFilas );

		if($pagina['records'] == 0){
			$pagina ['mensajeSinFilas'] = true;
		}

		$parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
		$parametrosNamespace->unlock ();
		$parametrosNamespace->listadoImpuestos = $pagina ['rows'];
		$parametrosNamespace->lock ();

		return $pagina;
	}

    public function buscarAction(){
        $this->_helper->viewRenderer->setNoRender ( true );

        $parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
        $parametrosNamespace->unlock ();

        $cantidadFilas = $this->getRequest ()->getParam ( "rows" );
        if (! isset ( $cantidadFilas )) {
                $cantidadFilas = $parametrosNamespace->cantidadFilas;
        }
        $page = $this->getRequest ()->getParam ( "page" );
        if (! isset ( $page )) {
                $page = 1 ;
        }

        $json_rowData = $this->getRequest ()->getParam ("data");
        $rowData = json_decode($json_rowData);

       $order = array('B.desc_modulo asc');
       
                $db = Zend_Db_Table::getDefaultAdapter();
                $select = $db->select()
                         ->from(array('A' => 'aplicacion'), 
                           array('A.cod_aplicacion','B.desc_modulo','A.desc_aplicacion','A.activo'))
                         ->join(array('B' => 'modulo_aplicacion'),'A.cod_modulo = B.cod_modulo',array('B.cod_modulo'));
                if($rowData->descripcion != null){         
                    $select->where("UPPER(A.desc_aplicacion) like '%".strtoupper(trim($rowData->descripcion))."%'");
                }
                $select->order($order);
//         die($select);
                $result = $db->fetchAll($select);
         
        $parametrosNamespace->lock ();
        
        $pagina = self::obtenerPaginas($result,$cantidadFilas,$page);
        $jsondata = $this->_helper->json ( $pagina );
        echo $jsondata;
    }

    public function eliminarAction(){
		$this->_helper->viewRenderer->setNoRender ( true );
		$id = $this->getRequest ()->getParam ( "id" );           
                $parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
		try{
                    $db = Zend_Db_Table::getDefaultAdapter();
                    $db->beginTransaction();
                    $servCon = new Application_Model_DataService($parametrosNamespace->Application_Model_DbTable);
                    $servCon->deleteRowById(array("cod_aplicacion"=>$id));
                    $db->commit();
		    echo json_encode(array("result" => "EXITO"));
	    }catch( Exception $e ) {
	    	echo json_encode(array("result" => "ERROR","mensaje"=>$e->getCode()));
			$db->rollBack();
		}
	}

	public function guardarAction(){
            $this->_helper->viewRenderer->setNoRender ( true );
            $json_rowData = $this->getRequest ()->getParam ( "parametros" );
            $rowData = json_decode($json_rowData);
            $applicationModel = new Application_Model_Aplicacion();
            self::almacenardatos($applicationModel,$rowData);
	}

	public function modificarAction(){
            $this->_helper->viewRenderer->setNoRender ( true );
            $json_rowData = $this->getRequest ()->getParam ( "parametros" );
            $rowData = json_decode($json_rowData);
            $rowClass = new Application_Model_Aplicacion();
		if($rowData->idRegistro != null){
				$rowClass->setCod_aplicacion($rowData->idRegistro);
			}
            self::almacenardatos($rowClass,$rowData);
	}

        public function almacenardatos($rowClass,$rowData){
     	try{
                $parametrosNamespace = new Zend_Session_Namespace ( 'parametros' );
     		$service = new Application_Model_DataService($parametrosNamespace->Application_Model_DbTable);
        	$db = Zend_Db_Table::getDefaultAdapter();
        	$db->beginTransaction();
                $rowClass->setCod_modulo(trim(utf8_decode($rowData->cod_modulo)));
                $rowClass->setDesc_aplicacion(trim(utf8_decode($rowData->desc_aplicacion)));
                $rowClass->setActivo($rowData->activo);
                
                $result = $service->saveRow($rowClass);
	    	$db->commit();
	    	echo json_encode(array("result" => "EXITO"));
        }catch( Exception $e ) {
	    	echo json_encode(array("result" => "ERROR","mensaje"=>$e->getCode()));
		$db->rollBack();
	}
    }
    public function modulodataAction() {
        
        $this->_helper->viewRenderer->setNoRender ( true );
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()
                 ->from(array('A' => 'modulo_aplicacion'), array('distinct(A.cod_modulo)', 'A.desc_modulo'))
                 ->where("A.activo = 'S'")
                 ->order(array('A.desc_modulo'));        
        $result = $db->fetchAll($select);
        $htmlResult = '<option value="-1">---Seleccione---</option>';
        foreach ($result as $arr) {
             $htmlResult .= '<option value="'.$arr["cod_modulo"].'">' .trim(utf8_decode($arr["desc_modulo"])).'</option>';	
        }
        echo  $htmlResult;
     }   

}

